<?php

namespace Trawind\Tenancy\Queue;


use Illuminate\Queue\Events\JobProcessing;
use Trawind\Rocketmq\Jobs\TenancyRocketMqJob;

class QueueTenancyBootstrapper extends \Stancl\Tenancy\Bootstrappers\QueueTenancyBootstrapper
{

    protected static function setUpJobListener($dispatcher)
    {
        $dispatcher->listen(JobProcessing::class, function ($event) {
            /** @var TenancyRocketMqJob $job */
            $job = unserialize($event->job->payload()['data']['command'] ?? '');
            $tenantId = $job->getTenantId();

            // The job is not tenant-aware
            if (!$tenantId) {
                return;
            }

            // Tenancy is already initialized for the tenant (e.g. dispatchNow was used)
            if (tenancy()->initialized && tenant('tenant_id') === $tenantId) {
                return;
            }

            // Tenancy was either not initialized, or initialized for a different tenant.
            // Therefore, we initialize it for the correct tenant.
            tenancy()->initialize(tenancy()->model()->where('tenant_id', $tenantId)->first());
        });
    }

    public function getPayload(string $connection)
    {
        if (!tenancy()->initialized) {
            return [];
        }

        if ($this->config["queue.connections.$connection.central"]) {
            return [];
        }

        return [
            'tenant_id' => tenant('tenant_id'),
        ];
    }

}